import { FC, createContext, useContext, useEffect, useState } from "react";
import { createStore } from "./redux";
import { useMounted } from "./useMount";

type S = ReturnType<typeof createStore> // string
const StoreCtx = createContext<Partial<S>>({})

interface IProvider {
  children: any
  store: S
}

export const Provider: FC<IProvider> = ({store, children}) => {
  return <StoreCtx.Provider value={store} >{children}</StoreCtx.Provider>
}

export const useDispatch = () => {
  const store = useContext(StoreCtx) as S
  return store.dispatch
}

export const useSelect = (cb: Function) => {
  const store = useContext(StoreCtx) as S
  const [_, render] = useState({})

  const getValue = () => {
    const state = store.getState()
    const value = cb(state)
    return value
  }
  /**
   * 如果value没有变化就不重新渲染
   */
  const renderPro = () => {
    const newValue = getValue()
    const oldValue = value
    if(oldValue !== newValue) render({})
  }

  useMounted(() => {
    const unSub = store.subscrible(renderPro)  // 订阅渲染函数
    return () => unSub()  // 取消订阅渲染函数
  })

  const value = getValue()
  return value
}
